/*
 * @Date: 2023-01-22 03:27:08
 * @LastEditors: 恶名扬 2080156129@qq.com
 * @LastEditTime: 2023-01-24 02:17:04
 * @FilePath: \campus-repair-platform\server\service\manage\repair.js
 */
/**
 * listRepair   获取报修单列表
 * queryRepair  查询报修单
 * stateRepair  修改报修单状态
 * examineRepair    审核报修单
 */

const { repairman } = require("../../common/distribution")
const repairStatement = require("../../common/sql_sentences/repair")

// const query = is_all ? { type_id, state } : `${type_id ? 'type_id = ' + type_id : ''} and (state = 1 or state = 6)`
exports.listRepair = async (req, res) => {
  try {
    const { type_id, a_id, a_number, r_number, page, pagesize, state } = req.body
    const query = { type_id, state, a_number, r_number, a_id }

    // 获取报修单总数
    let total,
      sqlStr = repairStatement.selectCount(query)
    let results = await RunSQL(sqlStr)
    total = results[0].total

    // 获取报修单列表
    sqlStr = repairStatement.selectLimit(query, page, pagesize)
    results = await RunSQL(sqlStr)
    res.successSend("", 10000, { row: results, total })
  } catch (error) {
    res.errSend(error)
  }
}

exports.queryRepair = async (req, res) => {
  try {
    const { id, state } = req.body
    // 查询报修单
    const sqlStr = repairStatement.select({ id, state })
    const results = await RunSQL(sqlStr)
    if (results.length !== 1) return res.successSend("没有查到报修单！", 10005) // 执行语句成功，但影响函数不等于 1
    return res.successSend("查询报修单成功！", 10000, results[0])
  } catch (error) {
    res.errSend(error) // 返回错误信息
  }
}

exports.stateRepair = async (req, res) => {
  try {
    const { newState, id } = req.body
    let query = { state: newState }
    if (newState < 3) {
      query.r_number = ''
      query.rtime = null
    }
    // 修改报修单状态
    const sqlStr = repairStatement.idUpdate(query, id)
    const results = await RunSQL(sqlStr)
    if (results.affectedRows !== 1)
      return res.successSend("修改报修单状态失败！", 10005) // 执行语句成功，但影响函数不等于 1
    return res.successSend("修改报修单状态成功！")
  } catch (error) {
    res.errSend(error)
  }
}

exports.examineRepair = async (req, res) => {
  const data = req.body
  try {
    if (data.is_adopt) {//通过报修单
      // 获取报修类型id
      let sqlStr = repairStatement.idSelect(data.id)
      let results = await RunSQL(sqlStr)
      if (results.length !== 1) return res.successSend("获取报修单信息失败！", 10005)

      // 自动分派维修人员
      results = await repairman(data.id, results[0].type_id, req.auth.job_number, results[0].a_id)
      res.successSend(results.message, results.code)
    } else {//退回报修单
      const sqlStr = repairStatement.idUpdate(
        { cause: data.cause, state: 3, a_number: req.auth.job_number },
        data.id
      )
      const results = await RunSQL(sqlStr)
      if (results.affectedRows !== 1)
        return res.successSend({ message: "报修单退回失败！", code: 10005 }) // 执行语句成功，但影响函数不等于 1
      res.successSend("报修单退回成功！")
    }
  } catch (error) {
    res.errSend(error)
  }
}
